package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 交易信息管理 service组件
 * @author : zjj
 * @date : 2021/2/7 15:01
 */

@Service
public class PaymentServiceImpl implements PaymentService {
    /**
     * 交易信息管理mapper组件
     */
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Override
    public void savePaymentInfo(OrderInfo orderInfo, String paymentType) {
        // 是否已经提交过订单
        QueryWrapper<PaymentInfo> query = new QueryWrapper<>();
        query.eq("order_id",orderInfo.getId())
                .eq("payment_type",paymentType);

        Integer count = paymentInfoMapper.selectCount(query);
        if(count > 0 ){
            return ;
        }
        // 构建交易信息
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
        paymentInfo.setSubject(orderInfo.getTradeBody());

        paymentInfo.setTotalAmount(orderInfo.getTotalAmount());

        paymentInfoMapper.insert(paymentInfo);

    }

    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, String paymentType) {
        QueryWrapper<PaymentInfo> query = new QueryWrapper<>();
        query.eq("out_trade_no",outTradeNo)
                .eq("payment_type",paymentType);

        return paymentInfoMapper.selectOne(query);
    }

    @Override
    public void paySuccess(String outTradeNO, String paymentType, Map<String, String> paramMap) {

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(paramMap.toString());
        paymentInfo.setTradeNo(paramMap.get("trade_no"));

        updatePaymentInfo(outTradeNO,paymentInfo);

    }

    @Override
    public void updatePaymentInfo(String outTradeNo, PaymentInfo paymentInfo) {
        QueryWrapper<PaymentInfo> query = new QueryWrapper<>();
        query.eq("out_trade_no",outTradeNo);
        paymentInfoMapper.update(paymentInfo,query);
    }
}
